package com.itcast.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.itcast.constant.MessageConstant;
import com.itcast.entity.Result;
import com.itcast.pojo.Member;
import com.itcast.service.OrderService;
import com.itcast.vo.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.UUID;

import static com.itcast.constant.RedisMessageConstant.SENDTYPE_ORDER;

@RequestMapping("order")
@RestController
public class OrderController {
    @Autowired
    JedisPool jedisPool;
    @Reference
    OrderService orderService;

    @RequestMapping("submit")
    private Result submit(@RequestBody OrderInfo orderInfo) {
        String token = orderInfo.getToken();
        String jedisToken = jedisPool.getResource().get("token");
        if (StringUtil.isEmpty(token) || StringUtil.isEmpty(jedisToken)) {
            return Result.error("非法请求");
        }
        String telephone = orderInfo.getTelephone();
        String validateCode = orderInfo.getValidateCode();
        String jedisCode = jedisPool.getResource().get(SENDTYPE_ORDER + telephone);
        if (StringUtil.isEmpty(jedisCode) || !jedisCode.equals(validateCode)) {
            return Result.error("验证码输入误");
        }
        return orderService.check(orderInfo);
    }

    //设置token
    @RequestMapping("getToken")
    public Result getToken() {
        String token = UUID.randomUUID().toString();
        jedisPool.getResource().set(token, token);
        return Result.success("", token);
    }



    @RequestMapping("getFamily")
    public Result getFamily(String token){
        try {
            String str = jedisPool.getResource().get(token);
            Member member = JSON.parseObject(str, Member.class);
            List<Member>  members = orderService.findFamily(member.getId());
            members.add(member);
            return Result.success("",members);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("非法请求");
        }

    }

    @RequestMapping("findById")
    public Result findById(Integer id ){

        return   orderService.findOrderSuccessByid(id);
    }

}
